package com.ytktt.study.week3.task346.gateway.config;

import com.google.common.collect.Maps;
import com.ytktt.study.week3.task346.gateway.properties.ApplicationProperties;
import com.ytktt.study.week3.task346.gateway.router.HttpEndpointRouter;
import com.ytktt.study.week3.task346.gateway.router.RandomHttpEndpointRouter;
import com.ytktt.study.week3.task346.gateway.router.RoundRibbonHttpEndpointRouter;
import com.ytktt.study.week3.task346.gateway.router.WeightHttpEndpointRouter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * router 配置
 *
 * @author ytk
 */
@Configuration
public class RouterConfig {

    @Bean
    @ConditionalOnProperty(prefix = ApplicationProperties.RouterProperties.PREFIX, name = "type", havingValue = "random", matchIfMissing = true)
    public HttpEndpointRouter randomHttpEndpointRouter() {
        return new RandomHttpEndpointRouter();
    }

    @Bean
    @ConditionalOnProperty(prefix = ApplicationProperties.RouterProperties.PREFIX, name = "type", havingValue = "round_ribbon")
    public HttpEndpointRouter roundRibbonHttpEndpointRouter() {
        return new RoundRibbonHttpEndpointRouter(new AtomicInteger(0));
    }

    @Bean
    @ConditionalOnProperty(prefix = ApplicationProperties.RouterProperties.PREFIX, name = "type", havingValue = "weight")
    public HttpEndpointRouter weightHttpEndpointRouter(ApplicationProperties applicationProperties) {
        List<String> proxyServers = applicationProperties.getProxyServers();
        Map<String, Integer> weightProxyServers = Maps.newHashMap();
        for (String proxyServer : proxyServers) {
            String[] split = proxyServer.split(",");
            weightProxyServers.put(split[0], Integer.valueOf(split[1]));
        }
        return new WeightHttpEndpointRouter(weightProxyServers);
    }

}
